//
//  PxMapViewController.m
//  Express
//
//  Created by 泰然财富 on 15/6/13.
//  Copyright (c) 2015年 泰然财富. All rights reserved.
//

#import "PxOauthWebViewController.h"

@implementation PxOauthWebViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGFloat baseHeight = [PxGlobal getBaseHeight:NO];
    
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    webView.height -= baseHeight;
    [self.view addSubview:webView];
    self.webView = webView;
    self.webView.delegate = self;
//    webView.autoresizesSubviews = YES;//自动调整大小
    
//    webView.scalesPageToFit =YES;//自动对页面进行缩放以适应屏幕
}

-(void)viewWillAppear:(BOOL)animated {
    NSDictionary *dic = self.incomingParam;
    [self setLogoTitleViewWithTitle:dic[@"name"]];
    
    if (dic[@"isNeedScale"] && [dic[@"isNeedScale"] intValue] == 1) {
//        _webView.autoresizesSubviews = YES;
        _webView.scalesPageToFit=YES;
        _webView.multipleTouchEnabled=YES;
        _webView.userInteractionEnabled=YES;
    }
    
    NSString *url = dic[@"url"];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    self.url = [NSURL URLWithString:url];
    NSURLRequest *request =[NSURLRequest requestWithURL:self.url];
    
    [self.webView loadRequest:request];
}

-(void) callback:(NSString *) url
{
    PxBaseOilNetCmd *cmd = [PxBaseOilNetCmd cmd];
    cmd.functionName = OAUTH_CODE_CALLBACK;
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] init];
    NSArray *arr = [url componentsSeparatedByString:@"?"];
    for (NSString *temp in [arr[1] componentsSeparatedByString:@"&"]) {
        NSArray *data = [temp componentsSeparatedByString:@"="];
        [paramDic setValue:data[1] forKey:data[0]];
    }
    [cmd.paramDic addEntriesFromDictionary:paramDic];
    
    cmd.businessSuccessHandler = ^(NSDictionary* dic)
    {
        LLDDLog(@"%@", dic);
        [PxNetSession sharedSession].token = [PxAccessToken beanWithDic:dic[RESULT_DATA]];
        
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        [defaults setObject:dic[RESULT_DATA] forKey:ACCESS_TOKEN];
        [defaults synchronize];
        
        [self popToLastControllerWithIncomingParam:nil];
    };
    
    cmd.businessErrorHandler = ^(NSDictionary* dic)
    {
        [LLAlertService sysAlertWithTip:dic[RESULT_DESC] withTitle:@"错误"];
    };
    
    cmd.errorHandler = ^(NSError* error)
    {
        
    };
    
    
    [LLRestEngine sendCommandRequest:cmd];
}

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)awebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString* scheme = [[request URL] scheme];
    NSString *currentURL = [request URL].absoluteString;
    // code回调，直接阻止
    if ([currentURL hasPrefix:[PxGlobal getConfig:@"ServerURL"]]) {
        LLDDLog(@"url = %@",[request URL].absoluteString);
        [self callback:currentURL];
        return NO;
    }
    //判断是不是https
    if ([scheme isEqualToString:@"https"]) {
        //如果是https:的话，那么就用NSURLConnection来重发请求。从而在请求的过程当中吧要请求的URL做信任处理。
        if (!self.authed) {
            _originRequest = request;
            NSURLConnection* conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
            [conn start];
            [awebView stopLoading];
            return NO;
        }
    }
    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//    NSString *url = webView.request.URL.absoluteString;
//    NSLog(@"%@", url);
//    if ([url hasPrefix:[PxGlobal getConfig:@"ServerURL"]]) {
//        [self popToLastControllerWithIncomingParam:nil];
//    }
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error
{
//    NSURL *url = error.userInfo[@"NSErrorFailingURLKey"];
//    NSLog(@"parameterString::%@",[url parameterString]);
//    [self.webView loadRequest:[NSURLRequest requestWithURL:url]];
//    [self popToLastControllerWithIncomingParam:nil];
}

#pragma mark ================= NSURLConnectionDataDelegate <NSURLConnectionDelegate>

- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response
{
    NSLog(@"%@",[request.URL parameterString]);

    return request;
    
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.authed = YES;
    //webview 重新加载请求。
    [_webView loadRequest:_originRequest];
    [connection cancel];
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    
    if ([challenge previousFailureCount]== 0) {
        _authed = YES;
        
        //NSURLCredential 这个类是表示身份验证凭据不可变对象。凭证的实际类型声明的类的构造函数来确定。
        NSURLCredential* cre = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        [challenge.sender useCredential:cre forAuthenticationChallenge:challenge];
    }
}
@end